package ingsw2.es2.fract;

public class Fraction {

	private long num;
	private long den;
	
	/**
	 * 
	 * @param num
	 * @param den
	 * @throws Exception
	 */
	public Fraction(long num, long den) throws Exception {
		if (den == 0)
			throw new Exception("Division by 0");
		this.num = num;
		this.den = den;
		if (this.den < 0){
			this.den *= -1;
			this.num *= -1;
		}
		simplify();
	}

	@Override
	public String toString() {
		return num + "/" + den;
	}
	
	@Override
	public boolean equals(Object f){
		if (this.num == ((Fraction)f).num && this.den == ((Fraction)f).den)
			return true;
		else
			return false;
	}
	
	public Fraction add(Fraction val) throws Exception {
		return new Fraction(this.num*val.den+val.num*this.den, this.den*val.den);
	}
	
	public Fraction subtract(Fraction sub) throws Exception {
		return new Fraction(this.num*sub.den-sub.num*this.den, this.den*sub.den);
	}
	
	public Fraction multiply(Fraction num) throws Exception {
		return new Fraction(this.num*num.num,this.den*num.den);
	}
	
	public Fraction divide(Fraction divisor) throws Exception {
		return new Fraction(this.num*divisor.den,this.den*divisor.num);
	}
	
	private void simplify(){
		long n = MCD(this.num,this.den);
		this.num /= n;
		this.den /= n;
	}
	
	public long MCD(long u, long v){
		if (u == 0)
			return v;
		if (v == 0)
			return u;

		long r = u % v;
	    while(r != 0) {
	        u = v;
	        v = r;
	        r = u % v;
	    }
	    return v;
	}
	
	public long mcm(long u, long v){
		return (u*v/MCD(u,v));
	}
	
}